<template>
  <div class="login-content">
    <div class="login-card">
      <div class="card-body">
        <div class="login-register">
          <!-- 顶部登录链接 -->
          <router-link class="login-link" to="/login/index">
            <span class="link-btn">登录</span>
          </router-link>

          <div class="register-container">
            <!-- 左侧二维码区域 -->
            <div v-if="loginSetting.useQrCode" class="qrcode-section hide-on-mobile" ref="qrcodeRef">
              <div v-loading="qrLoading" class="qrcode-box">
                <div v-if="loginSetting.mode !== 2" class="qrcode-title" v-html="loginSetting.name"></div>
                <div id="qrcode-container"></div>
                <div class="qrcode-info">请使用微信扫描二维码注册</div>
              </div>
            </div>

            <!-- 右侧注册表单区域 -->
            <div class="form-section" :class="loginSetting.useQrCode ? 'qrcode-padding' : ''">
              <div class="form-content">
                <div class="form__span_box">
                  <span class="form__span cur_form">账号密码注册</span>
                </div>
                <el-form ref="registerFormRef" :model="registerForm" :rules="registerFormRules" size="large" class="register-form">
                  <el-form-item prop="name">
                    <el-input v-model="registerForm.name" type="text" placeholder="请输入昵称" />
                  </el-form-item>
                  <el-form-item prop="account">
                    <el-input v-model="registerForm.account" type="text" placeholder="请输入手机号" />
                  </el-form-item>
                  <el-form-item label="" prop="code">
                    <GetVarCode v-model="registerForm.code" :phone="registerForm.account" />
                  </el-form-item>
                  <el-form-item label="" prop="password">
                    <el-popover
                      placement="top"
                      :width="350"
                      :visible="showTip"
                    >
                    <template #reference>
                      <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" show-password @focus="showTip = true" @blur="showTip = false" @input="validateNewPass" />
                    </template>
                    <div class="warn-content">
                      <ul>
                        <li>
                          <el-icon class="iconfont correct" v-if="warnNewFlag.notIncludeAccount"><Check /></el-icon>
                          <el-icon class="iconfont error" v-if="!warnNewFlag.notIncludeAccount"><Close /></el-icon>
                          <span>密码不能包含账号</span>
                        </li>
                        <li>
                          <el-icon class="iconfont correct" v-if="warnNewFlag.inputLength"><Check /></el-icon>
                          <el-icon class="iconfont error" v-if="!warnNewFlag.inputLength"><Close /></el-icon>
                          <span>密码长度大于等于8位</span>
                        </li>
                        <li>
                          <el-icon class="iconfont correct" v-if="warnNewFlag.complexityRequirement"><Check /></el-icon>
                          <el-icon class="iconfont error" v-if="!warnNewFlag.complexityRequirement"><Close /></el-icon>
                          <span>必须同时包含大写字母、小写字母、数字、特殊字符中的三者</span>
                        </li>
                      </ul>
                    </div>
                    </el-popover>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="large" type="primary" @click="handleRegister" class="register-btn">注册</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Check, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { register } from '@/api/user'
import GetVarCode from './components/GetVarCode'
import { useStore } from 'vuex'

const router = useRouter()
const store = useStore()
const loginSetting = computed(() => store.state.site.loginSetting)
// 密码验证
const showTip = ref(false)
const warnNewFlag = reactive({
  notIncludeAccount: false,
  inputLength: false,
  complexityRequirement: false
})
const validateNewPass = value => {
  if (value) {
    warnNewFlag.notIncludeAccount = !value.toLowerCase().includes(registerForm.value.account.toLowerCase())
    warnNewFlag.inputLength = value.length >= 8

    const hasUpperCase = /[A-Z]/.test(value)
    const hasLowerCase = /[a-z]/.test(value)
    const hasNumbers = /[0-9]/.test(value)
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)
    
    const conditions = [hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChar]
    const metConditions = conditions.filter(condition => condition).length
    
    warnNewFlag.complexityRequirement = metConditions >= 3
  } else {
    warnNewFlag.notIncludeAccount = false
    warnNewFlag.inputLength = false
    warnNewFlag.complexityRequirement = false
  }
}
const registerFormRef = ref(null)
const registerFormRules = reactive({
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!warnNewFlag.notIncludeAccount || !warnNewFlag.inputLength || !warnNewFlag.complexityRequirement) {
          callback(new Error('请按照密码规则设置密码'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    },
  ],
  account: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const registerForm = ref({
  name: '',
  account: '',
  password: '',
  code: ''
})

const handleRegister = () => {
  if (!registerFormRef.value) return
  registerFormRef.value.validate(async valid => {
    if (valid) {
      const res = await register(registerForm.value)
      if (res.code === 20000) {
        ElMessage.success('注册成功')
        router.push('/login/index')
      }
    }
  })
}

const qrLoading = ref(false)
const wechatQrcode = computed(() => store.state.site.wechatQrcode)
const qrcodeRef = ref(null)
const handleWechat = async () => {
  qrLoading.value = true
  // 提取wechatQrcode地址中的参数
  const url = new URL(wechatQrcode.value)
  const params = new URLSearchParams(url.search)
  const redirect_uri = params.get('redirect_uri')
  const state = params.get('state')
  const scope = params.get('scope')
  const appid = params.get('appid')

  try {
    let option = {
      id: 'qrcode-container',
      appid,
      redirect_uri,
      state,
      scope,
      stylelite: 1
    }
    // eslint-disable-next-line
    new WxLogin(option)
  } catch (error) {
    console.error('获取二维码失败:', error)
  } finally {
    qrLoading.value = false
  }
}
watch([wechatQrcode, qrcodeRef], (newVal) => {
  if (newVal[0] && newVal[1]) {
    handleWechat()
  }
}, { deep: true })
</script>

<style lang="scss" scoped>
.login-content {
  height: 100%;
  display: grid;
  place-items: center;
  z-index: 1;

  .login-card {
    position: relative;
    padding: 30px 20px 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    background: #fff;
    display: flex;
    flex-direction: column;
    z-index: 1;

    .card-body {
      flex: 1;
      overflow: hidden;
    }
  }
}

.login-register {
  min-height: 339px;
  height: 100%;
  overflow: hidden;

  .login-link {
    cursor: pointer;
    height: 70px;
    width: 70px;
    background-image: linear-gradient(to right bottom, rgb(186, 172, 255), rgb(48, 128, 255));
    clip-path: polygon(0% 0%, 100% 0%, 100% 100%);
    position: absolute;
    top: 0px;
    right: 0px;
    text-align: right;
    z-index: 2;

    .link-btn {
      font-size: 14px;
      color: #fff;
      font-weight: 500;
      position: relative;
      top: 10px;
      right: 7px;
    }
  }

  .register-container {
    display: flex;
    height: 100%;
    position: relative;
    z-index: 1;
    
    @media screen and (max-width: 768px) {
      justify-content: center;
      padding: 0 20px;
    }

    .qrcode-section {
      padding: 60px 70px 60px 50px;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 300px;
      box-sizing: border-box;
      border-right: 1px solid #e5e5e5;
      background: rgba(255, 255, 255, 0.9);

      &.hide-on-mobile {
        @media screen and (max-width: 768px) {
          display: none;
        }
      }

      .qrcode-box {
        text-align: center;

        .qrcode-title {
          font-size: 16px;
          color: #333;
          margin-bottom: 20px;
        }

        .qrcode-info {
          font-size: 14px;
          color: #999;
          margin-top: 20px;
        }
      }
    }

    .form-section {
      position: relative;
      width: 440px;
      box-sizing: border-box;
      background: rgba(255, 255, 255, 0.9);
      
      &.qrcode-padding {
        padding-left: 50px;
      }

      @media screen and (max-width: 768px) {
        padding-left: 0;
        width: 100%;
        max-width: 440px;
      }

      .form-content {
        padding-top: 20px;

        .form__span_box {
          margin-bottom: 30px;
          display: flex;
          gap: 40px;

          .form__span {
            font-size: 16px;
            color: #666;
            cursor: pointer;
            padding-bottom: 8px;
            border-bottom: 2px solid transparent;

            &.cur_form {
              color: var(--el-color-primary);
              border-bottom-color: var(--el-color-primary);
            }
          }
        }

        .register-form {
          :deep(.el-form-item) {
            margin-bottom: 20px;
            
            .el-input {
              --el-input-height: 50px;
            }
          }

          .register-btn {
            width: 100%;
            height: 50px;
            font-size: 16px;
          }
        }
      }
    }
  }
}

:deep(.el-form-item__error:before) {
  display: none !important;
}
</style>

<style>
.warn-content {
  background-color: #ffffff;
  border-radius: 4px;
  box-sizing: border-box;

  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  li {
    margin: 8px 0;
    
    .correct {
      color: #2cbf77;
    }
    .error {
      color: #ff5240;
    }
    
    span {
      margin-left: 6px;
    }
  }
}
</style>